package top.jnaw.jee.plugin.shiro;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;

public class RedisCache<K, V> implements Cache<K, V> {

  private static final String PREFIX = "SHRIO:";
  private static final String REDIS_PATTERN = PREFIX + "*";

  @Override
  public V get(K k) throws CacheException {
    return (V) top.jnaw.jee.utils.Cache.get(k);
  }

  @Override
  public V put(K k, V v) throws CacheException {
    return top.jnaw.jee.utils.Cache.set(k, v) ? v : null;
  }

  @Override
  public V remove(K k) throws CacheException {
    V v = (V) top.jnaw.jee.utils.Cache.get(k);
    if (null != v) {
      top.jnaw.jee.utils.Cache.del(k);
    }

    return v;
  }

  @Override
  public void clear() throws CacheException {
    top.jnaw.jee.utils.Cache.clean(REDIS_PATTERN);
  }

  @Override
  public int size() {
    return top.jnaw.jee.utils.Cache.keys(REDIS_PATTERN).size();
  }

  @Override
  public Set<K> keys() {
    return (Set<K>) top.jnaw.jee.utils.Cache.keys(REDIS_PATTERN);
  }

  @Override
  public Collection<V> values() {
    ArrayList<Object> result = new ArrayList<>();

    for (String k : top.jnaw.jee.utils.Cache.keys(REDIS_PATTERN)) {
      result.add(top.jnaw.jee.utils.Cache.get(k));
    }

    return (Collection) result;
  }
}
